package com.goethe.translator;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

public class UpdaterHttpRequest  extends AsyncTask<Activity , Void, Boolean> {
	private static final String TAG = "TranslationsUpdater";
	private static final String SQL_FILE_URL = "http://www.itbaonline.com.ar/translations_db";
	
	public static String getTranslationsFileName(){
		return Uri.parse(SQL_FILE_URL).getLastPathSegment();
	}

	@Override
	protected Boolean doInBackground(Activity... params) {
		boolean success = true;
		String translations = "";
		
		try{
			HttpClient httpclient = new DefaultHttpClient();
		    HttpResponse response = httpclient.execute(new HttpGet(SQL_FILE_URL));
		    StatusLine statusLine = response.getStatusLine();
		    
		    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
		        ByteArrayOutputStream out = new ByteArrayOutputStream();
		        response.getEntity().writeTo(out);
		        translations = out.toString();
		        out.close();
		    } else{
		        //Closes the connection.
		        response.getEntity().getContent().close();
		        success = false;
		        throw new IOException(statusLine.getReasonPhrase());
		    }
		} catch (Exception e) {
	    	success = false;
	        Log.e(TAG, e.getMessage(), e);
		}
		
		Log.d(TAG, "Received translations: " + translations);
		
		if(success){
			FileOutputStream outputStream = null;
		    try {
		    	String fileName = getTranslationsFileName();
		    	outputStream = params[0].getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE);
		    	outputStream.write(translations.getBytes());
		    	outputStream.close();
		    }
		    catch (Exception e) {
		    	success = false;
		        Log.e(TAG, e.getMessage(), e);
		    }
		}
		
		Log.d(TAG, "Updated translations file: " + success);
		
		return success;
	}

}
